package com.sky.handler;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


/**
 * @author wangqi
 * @date 2023/12/25 16:05
 */
//@RestControllerAdvice作用：让这个类的方法能够以JSON格式返回数据
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 如果项目中出现BaseException及其子类异常，都可以被捕获到。
     * @param e
     * @return
     */
    @ExceptionHandler
    public Result handlerException(BaseException e){
        log.info("错误:{}",e.getMessage());
        return Result.error(e.getMessage());
    }

    //java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'zhangwuji' for key 'employee.idx_username'
    @ExceptionHandler
    public Result handlerException(SQLIntegrityConstraintViolationException e){
        if(e.getMessage().contains("Duplicate entry")){
            //获取异常的消息
            String message = e.getMessage();
            String error_message = message.split(" ")[2] + MessageConstant.ALREADY_EXISTS; //用于已存在的消息
            return Result.error(error_message);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }
}
